import Vue from 'vue';
import VueRouter from 'vue-router';
import store from '@/store/index';
import addAsyncRouter from './addAsyncRouter';
Vue.use(VueRouter);

const routes = [
  {
    path: '/',
    redirect: '/home',
    name: 'App',
    component: () => import('@/App.vue'),
  },
];

const router = new VueRouter({
  base: process.env.BASE_URL, //路由前缀
  routes,
});

// 路由拦截，在url地址跳转之前执行
router.beforeEach(async (to, from, next) => {
  if (to.query.token) {
    // 1.token存下来
    store.commit('user/setToken', to.query.token);
    //  2.向后端验证token是否通过  分为通过和不通过
  }

  if (to.path == '/login') {
    store.commit('user/setMenuList', []);
    next();
  } else {
    if (store.state.user.token) {
      if (store.state.user.menuList.length === 0) {
        await addAsyncRouter(); //加载权限路由
        next({ ...to, replace: true });
      } else {
        next();
      }
    } else {
      next({ path: '/login' });
    }
  }

  next();
});

export default router;
